import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ConfirmationService } from 'primeng/primeng';
import { InterceptorService } from '../../../../share/interceptor.service';
import { SalaryEntity } from '../../../../models/salary-entity' ;
import { SearchSalaryEducationInfoComponent } from 'app/workspace/search-salary-education-info/search-salary-education-info.component';
 

@Component({
  selector: 'app-add-salary',
  templateUrl: './add-salary.component.html',
  styleUrls: ['./add-salary.component.css']
})
export class AddSalaryComponent implements OnInit {
    userId   = localStorage.getItem('userId');
  //private userId='001';//没有正式登录前，先用这个数据
  private msgs: any; //提示信息 
  private typeData = new Array();
  private salaryData = new Array();  //薪资实体集合
  companyOptions: string[];//公司
  company: string;//省集合
  salaryInfo :SalaryEntity = new SalaryEntity();
 
  btnDelete: boolean = true;
  btnAdd: boolean = true;
  btnEdit: boolean = false; 
  btnList: string[] = ["编辑"];
  title = ['月薪 (元)', '年薪', '所属公司', '职位', '调薪时间', '备注'];
  arrbutes = ["salary", "annualSalary", "companyName","possession", "salaryChangeTime","remark"];
  isLink = [false, false, false, false, false, false, false];
  paging: boolean = true;
    pageSize = 10;
    page = 1;
  total: number;

  sizeList = [5, 10, 20, 50];
  data = new Array();


  btnstyle = [
    { "color": "green" }]


 // 页面表格数据
  private tableUrl: string = "graduate-web/salary/findAll"+ '/' ;
  private deleteUrl: string = "graduate-web/salary/delete";
  // private getTableDateUrl="graduate-web/company/selectCompanySalaryByUserId";  //调用公司controller方法，无分页效果-ght-2018年3月7日
  private getTableDateUrl="graduate-web/salary/PageSelectSalaryByUserId";  //调用salaryController方法，有分页效果-ght-2018年3月7日
  operatorId:any;   //定义操作人变量-haoguiting-2018年3月7日

  constructor(private router: Router,
    private confirmationService: ConfirmationService,
    private http: InterceptorService) { }

  ngOnInit() {
    this.getData(true);
    console.log("查询公司开始了");
     this.getCompany(this.userId);
  }


  getData(isQuery?: boolean) {
    console.log("执行查询数据");
    this.operatorId = localStorage.getItem('userId');  //获得登录用户的id作为操作人的id-haoguiting-2018年3月7日
    // let url = this.tableUrl+ this.page + '/' + this.pageSize;
    // let url=this.getTableDateUrl+"/"+this.operatorId;  //无分页效果-hgt-2018年3月7日
    let url=this.getTableDateUrl+"/"+this.operatorId+ '/'+ this.page + '/' + this.pageSize;;  //有分页效果-hgt-2018年3月7日
    this.http.get(url).subscribe(
      res => {
        if (res.json().code === "0000") {
          this.data = res.json().data.list;//有分页效果-hgt-2018年3月7日
          // this.data = res.json().data; //无分页效果-hgt-2018年3月7日
          console.log("查询薪资数据");
          this.total=res.json().data.total; //获取页码
          for(var i=0;i<res.json().data.list.length;i++)
          {  
            let receiveDate=this.translateDate(new Date(res.json().data.list[i].salaryChangeTime));
            this.data[i].salaryChangeTime=receiveDate;
            console.info(receiveDate);
          }
        }
      }
    )
  }


  ch = {
    /** 每周第一天，0代表周日 */
    firstDayOfWeek: 0,
    /** 每周天数正常样式 */
    dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
    /** 每周天数短样式（位置较小时显示） */
    dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
    /** 每周天数最小样式 */
    dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
    /** 每月月份正常样式 */
    monthNames: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
    /** 每月月份短样式 */
    monthNamesShort: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
  };

  /**
   * 时间转化
   * @param date 日期
   */
  translateTime(date){
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); 
  }
  //将毫秒数转换成日期
  translateDate(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var a = date.getM
    return y + '-' + m + '-' + d;
  }

changepage(data:any){
  this.page=data.page;
  this.pageSize=data.pageSize;
  this.getData();
}
 
  // 打开修改模态框
  editOpen(index: any, editModal: HTMLElement) {
    editModal.style.visibility = 'visible';
    this.salaryInfo.id = this.data[index].id;    
    this.salaryInfo.salaryChangeTime = this.data[index].salaryChangeTime;
    this.salaryInfo.salary = this.data[index].salary;
    this.salaryInfo.timesPerYear = this.data[index].timesPerYear;
    this.salaryInfo.possession = this.data[index].possession;
    this.salaryInfo.annualSalary = this.data[index].annualSalary;
    this.salaryInfo.pcRelationId = this.data[index].pcRelationId;
    this.salaryInfo.remark = this.data[index].remark;
    this.salaryInfo.operator = this.data[index].operator;
    //this.salaryInfo.createTime = this.data[index].createTime;
    //document.getElementById('salary').focus();
    this.salaryInfo.salaryChangeTime = this.translateTime(new Date(this.salaryInfo.salaryChangeTime));  //转换时间格式-haoguiting-2018年3月15日
    
  }
  // 修改信息
  update(editModel: HTMLElement) {
    if(this.salaryInfo.pcRelationId ==undefined){
      console.log("请选择公司");
      this.showDialog("请选择公司！");
      return;
    }
    let editUrl = 'graduate-web/salary/update/';
    console.log("执行修改方法");
    this.salaryInfo.operator=localStorage.getItem('userName');   //获取操作人-hgt-2018年3月7日
    this.salaryInfo.operatorId = localStorage.getItem('userId');  //获得登录用户的id作为操作人的id-hgt-2018年3月7日
    this.salaryInfo.salaryChangeTime = this.translateTime(new Date(this.salaryInfo.salaryChangeTime)); //转换时间格式-haoguiting-2018年3月15日
    // this.personInfo.graduateDmtTime=this.translateTime(new Date(this.personInfo.graduateDmtTime));
    let body = JSON.stringify(this.salaryInfo);
    console.log('---------------------打印修改salaryInfo------------------------');    
    console.log(this.salaryInfo);
    this.http.post(editUrl, body).toPromise().then(
      res => {
        if (res.json().code = '0000') {
          this.showDialog(res.json().message);
          this.getData();
          this.close(editModel);
          console.log(res.json().message + '！！！！！');
        }

      }
    );
  }

  // 提示框
  display: boolean = false;
  messages: '';
  /**
   * 提示框
   */
  showDialog(string) {
    this.messages = string;
    this.display = true;
    let com = this;
    var t = setTimeout(function () { com.display = false }, 1500);
  }
  // 关闭模态框
  close(modal: HTMLElement) {
    modal.style.visibility = 'hidden';
    this.salaryInfo = new SalaryEntity();
  }
  /**
   *modal框可拖拽
  */
  // draggable() {
  //   $('.modal-dialog').draggable();
  // }




  //打开添加模态框
  addOpen(el: HTMLElement, addModal: HTMLElement) {

    addModal.style.visibility = 'visible';
    //document.getElementById('userId').focus();
  }

  //添加信息
  add(addModal: HTMLElement) {
    // 添加验证，如果有选择公司不允许添加薪资信息--hgt-2018年3月8日
    if(this.salaryInfo.pcRelationId ==undefined){
      console.log("请选择公司");
      this.showDialog("请选择公司！");
      return;
    }

    console.log(this.company+"公司信息展示");
    let addUrl = 'graduate-web/salary/insert/';
   console.log("添加前pcrelationId"+this.salaryInfo.pcRelationId);  
   this.salaryInfo.operator=localStorage.getItem('userName');   //获取操作人-hgt-2018年3月7日
   this.salaryInfo.operatorId = localStorage.getItem('userId');  //获得登录用户的id作为操作人的id-hgt-2018年3月7日
   this.salaryInfo.salaryChangeTime = this.translateTime(new Date(this.salaryInfo.salaryChangeTime)); //转换时间格式-haoguiting-2018年3月15日  
    let body = JSON.stringify(this.salaryInfo);
    console.log('---------------------打印添加salaryInfo------------------------');    
    console.log(this.salaryInfo);    
    this.http.post(addUrl, body).toPromise().then(
      res => {
        this.showDialog(res.json().message);
        this.getData();//回显
        this.close(addModal);
        console.log(res.json().message + '！！！！！');
      }
    );
  }

 
  deleteDatas(el: any) {
    // console.log(el);
      console.log(this.data[el[0]].id);
    // console.log(this.data[el[1]].id);
    // console.log(this.data[el[2]].id);
    //、、 let operator = '徐玲博-假数据';

    this.confirmationService.confirm({
      message: '你确定删除薪资信息吗？',
      accept: () => {
        for (let i = 0; i < el.length; i++) {
          let operator = this.data[el[i]].operator;
          let id = this.data[el[i]].id;
          console.log(this.data[el[i]]);
          let deleteUrl = 'graduate-web/salary/delete' + '/' + id + '/' + operator;
          console.log(deleteUrl + '执行到这了');

          let body = JSON.stringify(null);
          console.log(this.http.post(deleteUrl, body) + '执行到这了2');
          this.http.post(deleteUrl, body).subscribe(
            res => {             
              if (res.json().code != null && res.json().code == '0000') {
                this.showDialog(res.json().message);
                console.log(res.json().data + '执行到这了3');

                this.getData();
                this.total--;
              } else {
                this.showDialog(res.json().message);
                this.getData();
              }
            }
            );
        }
      }
    });
  }
 
  
  // //表格操作-于云丽-2017年12月29日
  // operatData(obj: any) {
  
  //   switch (obj.element.innerText) {
  //     case "编辑":
  //       localStorage.setItem("isEdit", JSON.stringify(true));      
  //       this.router.navigateByUrl('/workspace/person-info/add-person-info/add-salary');
  //       break;
  //   }
  // }


 operatData(obj: any, editModal: HTMLElement) {
    switch (obj.element.innerText) {
      case '编辑':
        this.editOpen(obj.data, editModal);
        break;
      default:
        break;
    }
  }
  // // 改变公司信息
  changeCompany(userId ) {

    // this.getCompany(userId);
    // console.log(userId);
  }
  

  getCompany(userId) {
    console.log("开始查询公司了2");
    // 方案1-后端方法
    this.operatorId = localStorage.getItem('userId');  //获得登录用户的id作为操作人的id-haoguiting-2018年3月7日
    let companyUrl = "graduate-web/company/selectCompanysByUserId/" + this.operatorId;
   
    //console.log(userId + "用户信息");
     
    this.http.get(companyUrl).subscribe(
      res => {
        if (res.json().code = "0000") {
          this.companyOptions = res.json().data;
          console.log("-------------------------打印companyOptions------------------------------")
          console.log(this.companyOptions);
          // console.log("绑定用户信息完毕,pcrelationID="+this.companyOptions.values);
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: "001",
              
              name: "中国人民银行"
            }, {
              id: "124",
              name: "保定"
            }, {
              id: "197",
              pid: "37",
              name: "廊坊"
            }, {
              id: "150",
              pid: "37",
              name: "张家口"
            }, {
              id: "84",
              pid: "37",
              name: "邯郸"
            }
          ];
          this.companyOptions = data;
        }
      }
    );
  }





 //表格添加-于云丽-2017年12月29日
  addInscription(obj: any) {
    localStorage.setItem("isEdit", JSON.stringify(false));
    this.router.navigateByUrl('/workspace/person-info/add-person-info/add-salary');
  }
  //链接列触发事件
  linkClick(i: number) {
    let index: number;
    if (this.paging) {
      index = i;
    } else {
      index = (this.page - 1) * this.pageSize + i;

    }
    //this.linkClickEmitData.emit(i);
    this.linkClickEmitData;
  }
  /**
   * 连接公司操作
   */
  linkClickEmitData(  ){
     
    this.router.navigateByUrl('/workspace/person-info/add-person-info/add-company');

  }




 
 /**
  * 将有格式的替换成没有格式的
  */
  onConvert(obj: any) {
    let showText;
    showText = obj.replace(/&nbsp;/g, ' ');
    showText = showText.replace(/<br>/g, '\n');
    return showText;
  }
  
  next() {
    this.router.navigateByUrl('/workspace/person-info/add-person-info/add-home'); //可以用相对路径吗
  }
}
